package com.merchant.home;

import java.util.ArrayList;
import java.util.HashMap;

import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.merchant.constant.Constants;
import com.merchant.home.MemberAccumulationActivity.RunTask;
import com.merchant.home.TouistAccumulationActivity.MyAdapter;
import com.merchant.home.TouistAccumulationActivity.ViewHolder;
import com.merchant.json.ReadJson;
import com.merchant.list.RefreshLayout;
import com.merchant.list.RefreshLayout.OnLoadListener;
import com.umeng.analytics.MobclickAgent;
import com.zjxfood.merchant.activity.R;

import android.app.Activity;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 返现明细
 * 
 * @author chenwei
 * 
 * 
 */
public class CumulativeBackMoneyActivity extends Activity implements
		OnClickListener, OnRefreshListener, OnLoadListener {
	private TextView title_text;
	private PullToRefreshListView lv;
	private ImageView cumulative_gain_back_image;// 返回
	private ProgressBar progressBar;
	// private TextView cumulative_time;
	private TextView back_money_agent;
	private HashMap<String, Object> mUserMapLists;
	private ArrayList<HashMap<String, Object>> mMap;
	private ArrayList<HashMap<String, Object>> mDataList;
	String back_money = null;
	private ArrayList<HashMap<String, Object>> addDataList;
	private MyAdapter adapter;
	private String page = "1";
	private int lastVisibleIndex;
	private int x = 1;
	private RunTask mRunTask;
	private LinearLayout help_ll_back;
	private PopupWindow popupWindow = null;
	private View popView = null;
	private ImageButton back_help_btn;
	// private RefreshLayout mSwipeLayout;
	// private View header;
	private int pagee = 1;
	private String label;
	// 标记数据请求状态，加载或刷新
	private int loading_state = Constants.DATE_ADAPTER_RESET;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cumulative_order);
		Intent intent = getIntent();
		back_money = intent.getStringExtra("back_money");
		init();
		mRunTask = new RunTask();
		mRunTask.execute("");
		// new Thread(getuserjhgroupbydate).start();
		setListener();
	}

	@SuppressWarnings("deprecation")
	private void init() {
		title_text = (TextView) findViewById(R.id.cumulative_gain_text);
		title_text.setText("返现明细");
		back_money_agent = (TextView) findViewById(R.id.back_money);
		back_money_agent.setText("¥" + back_money);
		cumulative_gain_back_image = (ImageView) findViewById(R.id.cumulative_gain_back_image);
		// cumulative_time = (TextView) findViewById(R.id.cumulative_time);
		cumulative_gain_back_image.setOnClickListener(this);
		// cumulative_time.setOnClickListener(this);
		lv = (PullToRefreshListView) findViewById(R.id.cumulative_order_listview);
		lv.setMode(Mode.BOTH);
		lv.setScrollingWhileRefreshingEnabled(false);
		help_ll_back = (LinearLayout) findViewById(R.id.help_ll_back);
		progressBar = (ProgressBar) findViewById(R.id.progressBar);
		back_help_btn = (ImageButton) findViewById(R.id.back_help_btn);
		back_help_btn.setOnClickListener(this);
		// help_ll_back.setOnClickListener(this);
		progressBar.setVisibility(View.VISIBLE);
		lv.setVisibility(View.GONE);
		// mSwipeLayout = (RefreshLayout)
		// findViewById(R.id.cumulative_order_swipe_ly);
		// header = getLayoutInflater().inflate(R.layout.header, null);
		// mSwipeLayout.setOnRefreshListener(this);
		// mSwipeLayout.setOnLoadListener(this);
		// mSwipeLayout.setColorSchemeResources(android.R.color.holo_green_dark,
		// android.R.color.holo_green_light,
		// android.R.color.holo_orange_light,
		// android.R.color.holo_orange_dark);
	}

	private void setListener() {
		lv.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(
					PullToRefreshBase<ListView> refreshView) {

				pagee = 1;
				label = DateUtils.formatDateTime(getApplicationContext(),
						System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
								| DateUtils.FORMAT_SHOW_DATE
								| DateUtils.FORMAT_ABBREV_ALL);
				lv.getLoadingLayoutProxy().setRefreshingLabel("正在刷新...");
				lv.getLoadingLayoutProxy().setPullLabel("下拉刷新");
				lv.getLoadingLayoutProxy().setReleaseLabel("松手刷新");
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(
						"上次更新:" + label);
				handler.sendEmptyMessageDelayed(4, 2000);
			}

			@Override
			public void onPullUpToRefresh(
					PullToRefreshBase<ListView> refreshView) {
				pagee++;
				loading_state = Constants.DATE_ADAPTER_ADD;
				label = DateUtils.formatDateTime(getApplicationContext(),
						System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
								| DateUtils.FORMAT_SHOW_DATE
								| DateUtils.FORMAT_ABBREV_ALL);
				lv.getLoadingLayoutProxy().setRefreshingLabel("正在加载...");
				lv.getLoadingLayoutProxy().setPullLabel("上拉加载更多");
				lv.getLoadingLayoutProxy().setReleaseLabel("松手加载");
				refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(
						"上次加载:" + label);
				handler.sendEmptyMessageDelayed(5, 2000);
			}
		});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent();
		switch (v.getId()) {
		case R.id.cumulative_gain_back_image:
			finish();
			break;
		case R.id.back_help_btn:
			showPopupWindow(v);
			break;
		}
	}

	public void onRefresh() {
		handler.sendEmptyMessageDelayed(4, 2000);
	}

	@Override
	public void onLoad() {
		// TODO Auto-generated method stub
		handler.sendEmptyMessageDelayed(5, 500);
	}

	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	/**
	 * 显示PopupWindow
	 */
	private void showPopupWindow(View anchor) {
		if (Constants.mtype != null) {
			if (Constants.mtype.equals("1")) {
				popView = LayoutInflater.from(this).inflate(
						R.layout.pop_help_backmoney, null);
			} else if (Constants.mtype.equals("2")) {
				popView = LayoutInflater.from(this).inflate(
						R.layout.pop_help_backmoney_salon, null);
			} else {
				popView = LayoutInflater.from(this).inflate(
						R.layout.pop_help_backmoney_cy, null);
			}
		}
		popupWindow = new PopupWindow(popView, LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		popupWindow.setBackgroundDrawable(new ColorDrawable(-00000000));// 设置背景透明
		popupWindow.setFocusable(true);// 获得焦点
		popupWindow.setOutsideTouchable(true);// 设置点击窗口外，popupWindow消失
		// popupWindow.showAsDropDown(anchor);// anchor 显示到该控件的正左下方，无偏移
		popupWindow.setAnimationStyle(R.style.AnimBottom);
		popupWindow.showAsDropDown(help_ll_back);
		popupWindow.showAtLocation(anchor, Gravity.BOTTOM, 0, 0);
		// popupWindow.showAsDropDown(anchor, xoff, yoff);//anchor 显示到该控件的 xoff,
		// yoff，有偏移
		// popupWindow.showAtLocation(parent, gravity, x, y);//相对于父类的控件的位置
		popupWindow.update();// 刷新内容
		// popupWindow.dismiss();
		popView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (popupWindow != null && popupWindow.isShowing()) {
					popupWindow.dismiss();
					popupWindow = null;
				}
				return false;
			}
		});
	}

	class RunTask extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... strs) {
			switch (x) {
			case 1:
				try {
					String ss = "uid=" + Constants.Id + "&page=" + page
							+ "&pagesize=10";
					String sign = Constants.sortsStr(ss);
					String str = Constants.getuserjhgroupbydate + sign
							+ "&uid=" + Constants.Id + "&page=" + page
							+ "&pagesize=10";
					String json = ReadJson.readParse(str);
					mUserMapLists = Constants.getJson2Object(json);
					Log.i("+++++++++++++++++++", mMap + "================");
					mDataList = Constants.getJsonArray(mUserMapLists
							.get("Data").toString());
					Log.i("msg", mDataList + "================");
					handler.sendEmptyMessageDelayed(1, 0);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					handler.sendEmptyMessageDelayed(3, 0);
					e.printStackTrace();
				}
				break;

			case 2:
				String ss = "uid=" + Constants.Id + "&page=" + page
						+ "&pagesize=10";
				String sign = Constants.sortsStr(ss);
				String str = Constants.getuserjhgroupbydate + sign + "&uid="
						+ Constants.Id + "&page=" + page + "&pagesize=10";
				String json;

				try {
					json = ReadJson.readParse(str);
					mUserMapLists = Constants.getJson2Object(json);
					addDataList = Constants.getJsonArray(mUserMapLists.get(
							"Data").toString());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					handler.sendEmptyMessageDelayed(3, 0);
					e.printStackTrace();
				}
				handler.sendEmptyMessageDelayed(2, 0);
				break;
			}

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			boolean hasMoreData = true;
			if (adapter != null) {
				adapter.notifyDataSetChanged();
			}
			lv.onRefreshComplete();
			super.onPostExecute(result);
		}
	}

	// //
	// Runnable getuserjhgroupbydate = new Runnable() {
	//
	// @Override
	// public void run() {
	// try {
	// // String ss = "uid=" + Constants.Id + "&page=" + 1 +
	// // "&pagesize="
	// // + 10;
	// // String sign = Constants.sortsStr(ss);
	// String str = Constants.getuserjhgroupbydate + "uid="
	// + Constants.Id + "&page=" + 1 + "&pagesize=" + 10;
	// String json = ReadJson.readParse(str);
	// mMap = Constants.getJsonObject(json);
	// Log.i("+++++++++++++++++++", mMap + "================");
	// mDataList = Constants.getJsonArray(mMap.get(0).get("Data")
	// .toString());
	// Log.i("msg", mDataList + "================");
	// handler.sendEmptyMessageDelayed(1, 0);
	// } catch (Exception e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// }
	// };
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				// mDataList.get(0).get("num").toString();
				// mDataList.get(0).get("time").toString();

				adapter = new MyAdapter(getApplicationContext(), mDataList);
				// lv.addHeaderView(header);
				lv.setAdapter(adapter);
				progressBar.setVisibility(View.GONE);
				lv.setVisibility(View.VISIBLE);
				// lv.setOnScrollListener(mScrollListener);
				lv.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(getApplicationContext(),
								CumulativeBackMoneyDetailActivity.class);
						Bundle bundle = new Bundle();
						bundle.putString("time",
								mDataList.get(arg2 - 1).get("time").toString());
						intent.putExtras(bundle);
						startActivity(intent);
					}
				});
				break;
			case 2:
				try {
					adapter.nofity(addDataList);
				} catch (Exception e) {
					// TODO: handle exception
					handler.sendEmptyMessageDelayed(6, 0);
				}
				break;
			case 3:
				progressBar.setVisibility(View.GONE);
				lv.setVisibility(View.VISIBLE);
				Toast.makeText(getApplicationContext(), "请检查您的网络链接!",
						Toast.LENGTH_SHORT).show();
				break;
			case 4:
				// try {
				// adapter.notifyDataSetChanged();
				// mSwipeLayout.setRefreshing(false);
				// } catch (Exception e) {
				// // TODO: handle exception
				// handler.sendEmptyMessageDelayed(6, 0);
				// }
				new RunTask().execute();
				break;
			case 5:
				// 更新数据
				// 更新完后调用该方法结束刷新
				x = 2;
				page = Integer.parseInt(page) + 1 + "";
				mRunTask = new RunTask();
				mRunTask.execute("");
				// mSwipeLayout.setLoading(false);
				break;

			case 6:
				Toast.makeText(getApplicationContext(), "请检查您的网络链接!",
						Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};
	OnScrollListener mScrollListener = new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (scrollState == OnScrollListener.SCROLL_STATE_IDLE
					&& lastVisibleIndex == adapter.getCount() - 1) {
				x = 2;
				page = Integer.parseInt(page) + 1 + "";
				mRunTask = new RunTask();
				mRunTask.execute("");
			}
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// 计算最后可见条目的索引
			lastVisibleIndex = firstVisibleItem + visibleItemCount - 1;
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { // 按下的如果是BACK，同时没有重复
			// do something here
			finish();
		}

		return super.onKeyDown(keyCode, event);
	}

	public final class ViewHolder {
		public ImageView ItemImage;
		public TextView ItemText;
		public TextView ItemTitle;
	}

	public class MyAdapter extends BaseAdapter {

		private LayoutInflater flater;
		private ArrayList<HashMap<String, Object>> mList;

		public MyAdapter(Context context,
				ArrayList<HashMap<String, Object>> list) {
			this.flater = LayoutInflater.from(context);
			this.mList = list;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mList.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		public void nofity(ArrayList<HashMap<String, Object>> list) {
			try {
				this.mList.addAll(list);
				notifyDataSetChanged();
			} catch (Exception e) {
				// TODO: handle exception
				handler.sendEmptyMessageDelayed(3, 0);
			}
		}

		@Override
		public View getView(int position, View converView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder hodler = null;
			if (converView == null) {
				hodler = new ViewHolder();
				converView = flater.inflate(R.layout.listview, null);

				hodler.ItemImage = (ImageView) converView
						.findViewById(R.id.ItemImage);
				hodler.ItemText = (TextView) converView
						.findViewById(R.id.ItemText);
				hodler.ItemTitle = (TextView) converView
						.findViewById(R.id.ItemTitle);
				converView.setTag(hodler);
			} else {
				hodler = (ViewHolder) converView.getTag();
			}
			hodler.ItemImage.setBackgroundResource(R.drawable.zzz);
			if (mList.get(position).get("money") != null) {
				hodler.ItemText.setText("¥"
						+ mList.get(position).get("money").toString());
			} else {
				hodler.ItemText.setText("¥" + "0.00");
			}

			if (mList.get(position).get("time") != null) {
				hodler.ItemTitle.setText(mList.get(position).get("time")
						.toString());
			} else {
				hodler.ItemTitle.setText("");
			}

			return converView;
		}

	}
}
